package com.example.thai.mydemo2.SqlDAO;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.example.thai.mydemo2.SqlAdapter.ApkEntity;
import com.example.thai.mydemo2.SqlAdapter.User;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by thai on 2014/10/30.
 * SQL的邏輯
 */
public class UserDAO {
    private static String DB_NAME = "xyz522.db";
    //private static String SQL = "SELECT * FROM N;";
    private static String SQL = "SELECT * FROM N ORDER BY _ID DESC;";
    private static final String TAG = "SQLITE";
    private Context ctx;

    public UserDAO(Context ctx) {
        super();
        this.ctx = ctx;
    }

    // copy Database
    private void copyDatabase(File dbFile) throws IOException {
        InputStream is = ctx.getAssets().open(DB_NAME);
        OutputStream os = new FileOutputStream(dbFile);

        byte[] buffer = new byte[1024];
        while (is.read(buffer) > 0) {
            os.write(buffer);
        }

        os.flush();
        os.close();
        is.close();
    }

    //開啟資料庫可讀取
    public SQLiteDatabase openReadDatabase() {
        File dbFile = ctx.getDatabasePath(DB_NAME);

        if (!dbFile.exists()) {
            try {
                File parentDir = new File(dbFile.getParent());
                if (!parentDir.exists()) {
                    parentDir.mkdir();
                }
                copyDatabase(dbFile);
            } catch (IOException e) {
                throw new RuntimeException("Error creating source database", e);
            }
        }

        return SQLiteDatabase.openDatabase(dbFile.getPath(), null,
                SQLiteDatabase.OPEN_READONLY);
    }

    public SQLiteDatabase openWriteDatabase() {
        File dbFile = ctx.getDatabasePath(DB_NAME);

        if (!dbFile.exists()) {
            try {
                File parentDir = new File(dbFile.getParent());
                if (!parentDir.exists()) {
                    parentDir.mkdir();
                }
                copyDatabase(dbFile);
            } catch (IOException e) {
                throw new RuntimeException("Error creating source database", e);
            }
        }

        return SQLiteDatabase.openDatabase(dbFile.getPath(), null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    // 讀取資料庫內容放到ArrayList
    public List<User> getAll(int position) {
        List<User> ret = new ArrayList<User>();
        switch(position){
            case 0:
                DB_NAME = "newsqlite.db";
                SQL = "SELECT * FROM NEWSQLITE;";
                break;
            case 1:
                DB_NAME = "mcd.db";
                SQL = "SELECT * FROM MCD;";
                break;
            case 2:
                DB_NAME = "kfc.db";
                SQL = "SELECT * FROM KFC;";
                break;
            case 3:
                DB_NAME = "custom.db";
                SQL = "SELECT * FROM CUSTOM;";
        }
        SQLiteDatabase db = this.openReadDatabase();
        Cursor cursor = db.rawQuery(SQL, null);
        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(0);
                String restaurant = cursor.getString(1);
                String name = cursor.getString(2);
                int money = cursor.getInt(3);
                byte[] image = cursor.getBlob(8);
                User u = new User(id, restaurant, name, money, image);
                ret.add(u);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return ret;
    }

    // SQlite取得產品圖片
    public Bitmap getBmp(int selectedIndex) {
        SQLiteDatabase db = this.openReadDatabase();
        Cursor cursor = db.rawQuery(SQL, null);
        Bitmap bmpout = null;
        if (cursor.moveToFirst()) {
            cursor.moveToPosition(selectedIndex);
            byte[] image = cursor.getBlob(7);
            try {
                bmpout = BitmapFactory.decodeByteArray(image, 0, image.length);
            }
            catch (Exception e)
            {
                bmpout = null;
            }
//            Log.i("TAG","getBmp = " + selectedIndex);
        }
        cursor.close();
        db.close();

        return bmpout;

    }
    //取得資料庫內的圖片回傳 byte[]陣列(目前沒有使用)
    public byte[] getByteMap(int selectedIndex) {
        SQLiteDatabase db = this.openReadDatabase();
        Cursor cursor = db.rawQuery(SQL, null);
        byte[] byteMap = null;


                cursor.moveToPosition(selectedIndex);
                byteMap = cursor.getBlob(7);
//            Log.i("TAG","getByteMap = " + selectedIndex);


        cursor.close();
        db.close();

        return byteMap;

    }


    // SQlite內的名稱
    public String getName(int position) {
        SQLiteDatabase db = this.openReadDatabase();
        Cursor cursor = db.rawQuery(SQL, null);
        if (cursor.moveToFirst()) {
            cursor.moveToPosition(position);
        }
        int nameColumnIndex = cursor.getColumnIndex("NAME");
        String name = cursor.getString(nameColumnIndex);

        cursor.close();
        db.close();

        return name;
    }

    // SQlite取得地址
    public String getAddress(int position) {
        SQLiteDatabase db = this.openReadDatabase();
        Cursor cursor = db.rawQuery(SQL, null);
        if (cursor.moveToFirst()) {
            cursor.moveToPosition(position);
        }
        int nameColumnIndex = cursor.getColumnIndex("ADDRESS");
        String address = cursor.getString(nameColumnIndex);

        cursor.close();
        db.close();

        return address;
    }

    // SQlite取得資料庫所有資料的總長度(目前沒有使用)
    public int getMaxID() {
        SQLiteDatabase db = this.openReadDatabase();


        int id = 0;
        final String MY_QUERY = "SELECT MAX(_ID) AS _ID FROM N";
        Cursor cursor = db.rawQuery(MY_QUERY, null);

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            id = cursor.getInt(cursor.getColumnIndex("_ID"));
        }
        cursor.close();
        db.close();
        return id;
    }

    //資料庫的刪除邏輯
    public boolean delete(int id) {
        SQLiteDatabase db = this.openWriteDatabase();
        try {
            db.delete("N", "_id=?", new String[] { id + "" });
//            Log.i("TAG","delete id =" + id);
        } catch (Exception ex) {
            Log.e(TAG, ex.getMessage());
            return false;
        }
        db.close();
        return true;
    }

    //資料庫的新增邏輯
    public boolean insert(ApkEntity u) {
        SQLiteDatabase db = this.openWriteDatabase();
        try {
            long uid = db.insert("N", null, u.toContentValues());
        } catch (Exception ex) {
            return false;
        }
        db.close();
        return true;
    }

}
